package com.rice.study.util;

import com.google.common.collect.Lists;
import com.rice.study.dao.Tester;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * @Auther: xuanqun
 * @Date: 2019/1/18 11:42
 * @Description:
 */
public class TesterSortUtil extends RecursiveTask<List<Tester>> {
    private static final long serialVersionUID = -3611254198265061349L;

    public static final int threshold = 2;
    private List<Tester> sourceList;

    public TesterSortUtil(List<Tester> sourceList) {
        this.sourceList = sourceList;
    }


    @Override
    protected List<Tester> compute() {
        if (sourceList == null){
            return null;
        }
        if (sourceList.size() > threshold){
            int middle = sourceList.size()/2;
            TesterSortUtil leftTask = new TesterSortUtil(sourceList.subList(0, middle));
            TesterSortUtil rightTask = new TesterSortUtil(sourceList.subList(middle+1, sourceList.size()));
            // 执行子任务
            leftTask.fork();
            rightTask.fork();

            //等待任务执行结束合并其结果
            List<Tester> leftResult = leftTask.join();
            List<Tester> rightResult = rightTask.join();

            //合并子任务
            leftResult.addAll(rightResult);
            return leftResult;
        }else {
            if (sourceList.size() ==  1 || sourceList.get(0).getSort() <= sourceList.get(1).getSort()){
                return sourceList;
            }else {
                List<Tester> result = Lists.newArrayList();
                result.add(sourceList.get(1));
                result.add(sourceList.get(0));
                return result;
            }
        }
    }
}
